﻿using MVCForum.Web.Identity.EF.Entities;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;

namespace MVCForum.Web.Identity.EF {

	public class IdentityContext : DbContext {

		public IdentityContext() : base("DefaultConnection") { }

		public IdentityContext(String nameOrConnectionString) : base(nameOrConnectionString) { }

		public IDbSet<User> Users { get; set; }
		public IDbSet<Role> Roles { get; set; }

		public IDbSet<UserLogin> UserLogins { get; set; }
		public IDbSet<UserClaim> UserClaims { get; set; }

		public IDbSet<UserRole> UserRoles { get; set; }

		protected override void OnModelCreating(DbModelBuilder modelBuilder) {

			modelBuilder.Entity<User>().Property(u => u.UserName).IsRequired();
			modelBuilder.Entity<User>().Property(u => u.EmailAddress).IsRequired();
			modelBuilder.Entity<User>().Property(u => u.Created).IsRequired();
			modelBuilder.Entity<User>().Property(u => u.LastVisit).IsRequired();
			modelBuilder.Entity<User>().Property(u => u.Locked).IsRequired();
			modelBuilder.Entity<User>().Property(u => u.Approved).IsRequired();
			modelBuilder.Entity<User>().Property(u => u.LastPasswordFailure).IsRequired();
			modelBuilder.Entity<User>().Property(u => u.PasswordFailures).IsRequired();
			modelBuilder.Entity<User>().Property(u => u.LastLockout).IsRequired();
			modelBuilder.Entity<User>().HasMany<UserRole>(u => u.Roles);

			modelBuilder.Entity<UserLogin>().HasRequired(u => u.User);
			modelBuilder.Entity<UserClaim>().HasRequired(u => u.User);

			modelBuilder.Entity<Role>().Property(u => u.Name).IsRequired();

			modelBuilder.Entity<UserRole>().HasKey(r => new { RoleId = r.RoleId, UserId = r.UserId });

			modelBuilder.Entity<UserLogin>().HasKey(ul => new { UserId = ul.UserId, LoginProvider = ul.LoginProvider, ProviderKey = ul.ProviderKey });

			base.OnModelCreating(modelBuilder);
		}

		protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<Object, Object> items) {
			return base.ValidateEntity(entityEntry, items);
		}
	}
}